package com.internetCafes.spms.common.module.mybatis.plugin;

import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class StartSysListener implements ApplicationListener<ContextRefreshedEvent> {

    private static Logger log = LoggerFactory.getLogger(StartSysListener.class);

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        this.addMyInterceptor();
    }

    /**
     * 为了兼容PageHelper的分页插件，拦截器再分页插件加载之后加载
     * 参考https://www.jianshu.com/p/8dc9f8a4cce9
     */
    private void addMyInterceptor() {
//        log.debug("添加自定义Mybatis SQL拦截器.");
        MultiTenancyInterceptor interceptor = new MultiTenancyInterceptor();
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
        }
    }

}
